<template>
  <div class="min-h-screen bg-white dark:bg-gray-900 w-full">
    <!-- 头部导航 -->
    <AppHeader />
    
    <!-- 筛选栏 -->
    <FilterBar 
      :selected-sector="filters.sector"
      :selected-exchange="filters.exchange"
      @update:sector="handleUpdateFilters({ sector: $event })"
      @update:exchange="handleUpdateFilters({ exchange: $event })"
    />
    
    <!-- 主内容区域 - 4x4网格布局 -->
    <main class="w-full px-4 py-4">
      <!-- 加载状态 -->
      <div v-if="loading" class="flex items-center justify-center py-20">
        <div class="flex items-center space-x-2">
          <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
          <span class="text-gray-600 dark:text-gray-400">加载中...</span>
        </div>
      </div>
      
      <!-- 错误状态 -->
      <div v-else-if="error" class="flex items-center justify-center py-20">
        <div class="text-center">
          <div class="text-red-600 dark:text-red-400 text-lg font-medium mb-2">
            {{ error }}
          </div>
          <button 
            @click="refreshData"
            class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
          >
            重试
          </button>
        </div>
      </div>
      
      <!-- 数据为空 -->
      <div v-else-if="filteredInstruments.length === 0" class="flex items-center justify-center py-20">
        <div class="text-center">
          <div class="text-gray-500 dark:text-gray-400 text-lg mb-2">
            暂无数据
          </div>
          <div class="text-gray-400 dark:text-gray-500 text-sm">
            请尝试调整筛选条件
          </div>
        </div>
      </div>
      
      <!-- 响应式网格布局 - 自适应屏幕大小 -->
      <div v-else class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3 sm:gap-4 w-full">
        <div v-for="instrument in filteredInstruments.slice(0, 16)" :key="instrument.id" class="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-3 sm:p-4 hover:shadow-lg transition-shadow">
          <!-- 产品信息头部 -->
          <div class="flex items-center justify-between mb-3">
            <div class="flex-1">
              <h3 class="text-sm font-medium text-gray-900 dark:text-white mb-1">
                {{ instrument.name }}
              </h3>
              <div class="flex items-center space-x-2 text-xs text-gray-500 dark:text-gray-400">
                <span>{{ instrument.symbol }}</span>
                <span>{{ instrument.daysToExpiry }}天</span>
              </div>
            </div>
          </div>
          
          <!-- 价格和波动率信息 -->
          <div class="mb-3">
            <div class="flex items-center justify-between mb-1">
              <div class="text-lg font-bold text-gray-900 dark:text-white">
                {{ formatPrice(instrument.currentPrice) }}
              </div>
              <div :class="[
                'text-sm font-medium',
                instrument.change >= 0 ? 'text-green-600 dark:text-green-400' : 'text-red-600 dark:text-red-400'
              ]">
                {{ instrument.change >= 0 ? '+' : '' }}{{ formatPrice(instrument.change) }}%
              </div>
            </div>
            <div class="flex items-center justify-between text-sm">
              <div class="text-gray-600 dark:text-gray-400">
                波动率: <span class="font-medium text-gray-900 dark:text-white">{{ formatPrice(instrument.impliedVol) }}%</span>
              </div>
              <div :class="[
                'text-sm font-medium',
                instrument.volChange >= 0 ? 'text-green-600 dark:text-green-400' : 'text-red-600 dark:text-red-400'
              ]">
                {{ instrument.volChange >= 0 ? '+' : '' }}{{ formatPrice(instrument.volChange) }}
              </div>
            </div>
          </div>
          
          <!-- 合约选择按钮 -->
          <div class="flex items-center space-x-1 mb-3">
            <button 
              v-for="contract in instrument.contracts" 
              :key="contract"
              :class="[
                'px-2 py-1 text-xs rounded',
                contract === instrument.selectedContract
                  ? 'bg-gray-800 dark:bg-gray-600 text-white'
                  : 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600'
              ]"
              @click="selectContract(instrument.id, contract)"
            >
              {{ contract }}
            </button>
          </div>
          
          <!-- 图表区域 -->
          <div class="h-48 w-full">
            <VolatilityChart 
              :instrument="instrument" 
              :height="180"
            />
          </div>
        </div>
      </div>
      
      <!-- 底部信息 -->
      <div class="mt-6 text-center text-sm text-gray-500 dark:text-gray-400">
        数据更新时间: {{ lastUpdateTime }}
      </div>
    </main>
  </div>
</template>

<script setup lang="ts">
import type { SectorType, ExchangeType } from '~/types/market'
import VolatilityChart from '~/components/charts/VolatilityChart.vue'

// 页面元数据
useSeoMeta({
  title: 'OpenVlab - 波动率概览',
  description: 'OpenVlab波动率分析平台，提供实时市场波动率数据和期权分析工具',
  keywords: ['波动率', '期权', '金融', '分析', 'OpenVlab']
})

// 使用市场数据
const {
  filteredInstruments,
  loading,
  error,
  filters,
  updateFilters,
  refreshData
} = useMarketData()

// 更新时间
const lastUpdateTime = ref('')

// 格式化时间
const formatTime = (date: Date) => {
  return date.toLocaleTimeString('zh-CN', { 
    hour12: false,
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 格式化价格
const formatPrice = (price: number) => {
  if (price >= 1000) {
    return price.toLocaleString('zh-CN', { 
      minimumFractionDigits: 2,
      maximumFractionDigits: 2 
    })
  } else if (price >= 1) {
    return price.toFixed(2)
  } else {
    return price.toFixed(3)
  }
}

// 更新筛选条件
const handleUpdateFilters = (newFilters: { sector?: SectorType; exchange?: ExchangeType }) => {
  updateFilters(newFilters)
}

// 选择合约
const selectContract = (instrumentId: string, contract: string) => {
  // 这里可以添加合约选择的逻辑
  console.log(`选择合约: ${instrumentId} - ${contract}`)
}

// 模拟实时更新时间
onMounted(() => {
  lastUpdateTime.value = formatTime(new Date())
  
  const interval = setInterval(() => {
    lastUpdateTime.value = formatTime(new Date())
  }, 1000)
  
  // 监听刷新事件
  const handleRefreshEvent = () => {
    refreshData()
  }
  
  window.addEventListener('refresh-market-data', handleRefreshEvent)
  
  onUnmounted(() => {
    clearInterval(interval)
    window.removeEventListener('refresh-market-data', handleRefreshEvent)
  })
})
</script>
